package login

import (
	"github.com/gin-gonic/gin"
	"go-interview-forum/global"
	"go-interview-forum/resp"
	"go-interview-forum/service/login"
	"regexp"
)

type LoginInfo struct {
	Mobile string `json:"mobile"`
	Code   string `json:"code"`
}

func UserLogin(c *gin.Context) {
	var loginInfo LoginInfo
	err := c.ShouldBind(&loginInfo)
	if err != nil {
		resp.QueryErrorResp(c, "参数错误")
		return
	}

	if loginInfo.Mobile == "" {
		resp.QueryErrorResp(c, "手机号不能为空")
		return
	}

	if loginInfo.Code == "" {
		resp.QueryErrorResp(c, "验证码不能为空")
		return
	}

	compile, err := regexp.Compile(global.MOBILE_REGEXP)
	if err != nil {
		resp.ServerErrorResp(c, resp.SERVER_ERR, "正则编译错误")
		return
	}

	if !compile.Match([]byte(loginInfo.Mobile)) {
		resp.QueryErrorResp(c, "手机号格式错误")
		return
	}

	token, err := login.UserLogin(loginInfo.Mobile, loginInfo.Code)
	if err != nil {
		resp.QueryErrorResp(c, err.Error())
		return
	}

	resp.SuccessResp(c, token)
}
